//
//  HMPictureView.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/26.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
let pictureViewCellId =  "pictureViewCellId"
let PictureMargin: CGFloat = 3
let PictureMaxWidth = ScreenWidth - 2 * StatusCellMargin
let PictureWidth = (PictureMaxWidth - 2 * PictureMargin ) / 3.0
let pictureHeight: CGFloat = 150
class HMPictureView: UICollectionView{
    
    var pictures: [HMPicture]?{
        didSet{
           let pictureSize = self.getItemSize()
            self.snp_updateConstraints(closure: { (make) in
                make.size.equalTo(pictureSize)
            })
            reloadData()
        }
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = PictureMargin
        flowLayout.minimumInteritemSpacing = PictureMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        self.dataSource = self
        self.delegate = self
        self.backgroundColor = UIColor.darkGrayColor()
        registerClass(HMPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:根据图片个数计算大小
    func getItemSize() -> CGSize{
        let imageCount = pictures?.count ?? 0
        if imageCount == 0 {
            
            return CGSize.zero
        }
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        if imageCount == 1 {
            let imageSize = CGSize(width: 100, height: 150)
            flowLayout.itemSize = imageSize
            return imageSize
        }

        
        flowLayout.itemSize = CGSize(width: PictureWidth, height: PictureWidth)
        if imageCount == 2 {
            let width = PictureMargin + 2 * PictureWidth
            return CGSize(width: width, height: PictureWidth)
        }
        if imageCount == 4 {
             let width = PictureMargin + 2 * PictureWidth
            return CGSize(width: width, height: width)
        }
        
        let row = CGFloat(((pictures?.count)! - 1) / 3 + 1)
        let height = row * PictureWidth + (row - 1) * PictureMargin
        return CGSize(width: PictureMaxWidth, height: height)
    }

}
//MARK:实现数据源方法
extension HMPictureView: UICollectionViewDataSource{
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            //
            return self.pictures?.count ?? 0
        }
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! HMPictureViewCell
            cell.picture = self.pictures![indexPath.item]
            return cell
        }
}
class HMPictureViewCell: UICollectionViewCell{
    var picture: HMPicture?{
        didSet{
            let url = NSURL(string: picture?.thumbnail_pic ?? "")
            imageView.sd_setImageWithURL(url)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    private func setupUI(){
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self.contentView)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    
    }()
}
extension HMPictureView: UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrower = SDPhotoBrowser()
        photoBrower.sourceImagesContainerView = self
        photoBrower.imageCount = pictures?.count ?? 0
        photoBrower.currentImageIndex = indexPath.item
        photoBrower.delegate = self
        photoBrower.show()
    }
}
extension HMPictureView: SDPhotoBrowserDelegate{
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let index = NSIndexPath(forItem: index, inSection: 0)
        let cell = cellForItemAtIndexPath(index) as! HMPictureViewCell
        return cell.imageView.image
    }
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pictures![index].thumbnail_pic
        let pngStr = urlString?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        let url = NSURL(string: pngStr!)
        return url
    }
}